package com.lwphk.easydocs.core;

import java.lang.reflect.Field;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ValueConstants;

import com.lwphk.easydocs.annotations.DocField;
import com.lwphk.easydocs.annotations.DocNil;
import com.lwphk.easydocs.core.vo.DocsBasicInfo;
import com.lwphk.easydocs.core.vo.MethodInfo;
import com.lwphk.easydocs.core.vo.ParamInfo;
import com.lwphk.easydocs.util.ClassReaderUtil;

public abstract class ParameterParseAbstract {

	
	public List<ParamInfo> getObjFields(Class<?> clazz) {
		Map<String, String> fieldMap = DocsBasicInfo.GlobalFieldMappingMap;
		List<ParamInfo> list = new ArrayList<ParamInfo>();
		List<Field> fieldArr = ClassReaderUtil.getAllFields(clazz, true, true);
		for (Field field : fieldArr) {
			if(field.getAnnotation(DocNil.class) != null) continue;
			
			ParamInfo pi = new ParamInfo();
			if(field.getType().isArray()) {
				pi.setType("Array");
			}else {
				pi.setType(field.getType().getName());
			}
			pi.setRequire(false);
			pi.setName(field.getName());
			
			DocField docField = field.getAnnotation(DocField.class);
			if (docField != null) {
				if (StringUtils.isNotBlank(docField.name())) {
					pi.setRemark(docField.name());
				} else {
					pi.setRemark(docField.remark());
				}
			} else {
				if (StringUtils.isNotBlank(fieldMap.get(pi.getName()))) {
					pi.setRemark(fieldMap.get(pi.getName()));
				}

			}
			
			
			list.add(pi);
		}

		return list;
	}
	
	public ParamInfo buildBasicInfo(Parameter e) {
		Map<String, String> fieldMap = DocsBasicInfo.GlobalFieldMappingMap;
		ParamInfo pi = new ParamInfo();
		pi.setType(e.getType().getName());
		pi.setRequire(false);
		pi.setName(e.getName());

		RequestParam rp = e.getAnnotation(RequestParam.class);
		if (rp != null) {
			pi.setRequire(rp.required());
			pi.setDefaultValue(rp.defaultValue());
			if (StringUtils.isNotBlank(rp.name())) {
				pi.setName(rp.name());
			} else if (StringUtils.isNotBlank(rp.value())) {
				pi.setName(rp.value());
			}
		}

		DocField docField = e.getAnnotation(DocField.class);
		if (docField != null) {
			if (StringUtils.isNotBlank(docField.name())) {
				pi.setRemark(docField.name());
			} else {
				pi.setRemark(docField.remark());
			}
		} else {
			if (StringUtils.isNotBlank(fieldMap.get(e.getName()))) {
				pi.setRemark(fieldMap.get(e.getName()));
			}

		}

		if (ValueConstants.DEFAULT_NONE.equals(pi.getDefaultValue())) {
			pi.setDefaultValue("");
		}

		return pi;
	}
	
	
	public abstract void parse(Parameter e, MethodInfo mi) throws Exception;
}
